#include"stdTcpServer.h"
#include<iostream>
#include<unistd.h>
#include<time.h>
#include<cstring>
#include"stdShared.h"
#include"function.h"
#include"messageHandle.h"
#include"threadpool.h"
#include<json-c/json.h>
using namespace std;
#define BUFFER_SIZE 1024
void *handlCientInfo(void * arg)
{
    //线程分离
    pthread_detach(pthread_self());
    stdTcpSocketPtr clientInfo = *static_cast<stdTcpSocketPtr*>(arg);
    int readBytes=0;
    Msg msg;
    //清空脏数据
    memset(&msg, 0, sizeof(msg));
    MessageHandle handles(clientInfo);
    string buffer;
    buffer.clear();
    while (1)
    {
        // readBytes=clientInfo->recvMessage(&msg, sizeof(msg));
        readBytes=clientInfo->recvMessage(buffer);
        if(readBytes<=0)
        {
            cout << "readBytes <= 0" << endl;
            break;
        }
        else
        {
            //客户端有数据过来
            cout <<"buffer:"<< buffer << endl;
            // cout << "msg.type:" << msg.type << endl;
            // handles.handleMessage(msg);
            //buffer是json字符串
            //将json字符串转成json对象
            json_object *jsonObj= json_tokener_parse(buffer.c_str());

            //根据key得到value
            const char* type=json_object_get_string(json_object_object_get(jsonObj, "type"));
            const char* username=json_object_get_string(json_object_object_get(jsonObj, "username"));
            const char* passwd=json_object_get_string(json_object_object_get(jsonObj, "passwd"));
            cout << "type:" << type << endl;
            cout << "username:" << username << endl;
            cout << "passwd:" << passwd <<endl;

        }
        //清空缓冲区
        buffer.clear();
    }
    return NULL;
}
int main()
{
    //创建线程池对象
    ThreadPool pool(3, 8, 20);
    // 创建服务器对象
    StdTcpServer server;
    //设置侦听
    bool res=server.SetListen(8080);
    if(res==false)
    {
        perror("listen:");
        _exit(-1);
    }
    cout << "正在监听" <<endl;

    // 建立连接

    int ret = 0;
    while (1)
    {
        stdTcpSocketPtr clientInfo= server.getClientSock();
        #if 0
        pthread_t threadId;
        ret=pthread_create(&threadId, NULL, handlCientInfo, &clientInfo);
        if(ret!=0)
        {
            perror("thread create:");
            _exit(-1);
        }
        #else
        pool.addTask(handlCientInfo, new stdTcpSocketPtr(clientInfo));
        
        #endif
        sleep(1);
    }

    return 0;
}